import { action, observable } from "mobx";
import { WeaTools, WeaLocaleProvider,WeaInputLocale } from 'ecCom'
import { each } from 'lodash';
import QuickTableStore from "./excel/QuickTableStore";
import CellType from './excel/celltypes';
import FormulaAPI from '../apis/formula';
import API from '../apis/excel';
import { register, setRightMenu } from './excel/command';
import getFont from '../utils/getFont';
import getCellName from '../utils/getCellName';
import * as TopActions from './excel/action/top';
import * as CommonAction from './excel/action/common';
import MenuAction from './excel/action/menu';
import AddSelectOptionsStore from './dialog/addSelectOptionsStore';
import AddFixphareStore from './dialog/addFixphareStore';
import AddSelectTreeStore from './dialog/addSelectTreeStore'
import TemplateBrowserStore from "./dialog/templateBrowserStore";
import DataSourceDialogStore from "./dialog/DataSourceDialogStore";
import AceEditorDialogStore from "./dialog/AceEditorDialogStore";
import CodeEditorDialogStore from "./dialog/CodeEditorDialogStore";
import { loadPageDs, loadPageFieldAssign } from "../apis/dataset";
import FieldPropsStore from "./excel/FieldPropsStore";
import { FieldPropsType } from "../constants/excel";
import CustomFunction from "./excel/function/CustomFunction";
import ConditionDialogStore from "./dialog/ConditionDialogStore";
import FieldAssignDialogStore from "./dialog/FieldAssignDialogStore";
const getLabel = WeaLocaleProvider.getLabel;
const getCurrentLabel = WeaInputLocale.getCurrentLabel;
export default class ExcelDesignerStore {
    @observable isInit = false;
    @observable loading = false;
    @observable workbook;
    @observable readonly = false;
    appid = '';
    @observable activeCellStyle = {};
    @observable activeCellName = '';

    // quick table
    @observable quickTableVisible = false;
    @observable quickTableStore;
    @observable templateBrowserStore = new TemplateBrowserStore("excel");
    @observable disabledSignFields = true;
    @observable clearFieldDisabled = false;
    @observable deleteTableDisabled = true;
    @observable setFieldTypeDisabled = false;
    @observable isAutoFillin = false;
    @observable isAutoFillinDisabled = true;
    @observable browserAutoFillin;
    @observable nodetailJson = new Map();
    @observable dataSourceList = [];
    @observable autoFitSheetMap = {};
    @observable sheetAutoFit = false;
    @observable dataSourceStore = new DataSourceDialogStore();
    @observable aceEditorStore = new AceEditorDialogStore(this);
    @observable codeEditorStore = new CodeEditorDialogStore();
    @observable fieldAssignStore = new FieldAssignDialogStore();
    @observable fieldProps;
    @observable selection = '1*1';
    @observable isformatpainter = false;
    @observable undoDisabled = true;
    @observable redoDisabled = true;
    @observable rowControl = {};
    @observable conditionDialogStore = new ConditionDialogStore();//条件参数
    @observable fieldAssignList = [];
    @observable detailSelectCellTypesMap = {};
    @observable detailSelectCellTypeValueMap = {};
    @observable customdetailSelectCellTypeValueMap = {};
    @observable customdetailSelectCellTypesMap = {};
    @observable mainSelectCellTypesMap = {};
    @observable mainSelectCellTypeValueMap = {};
    @observable sheetnameChangeRecord = {};
    @observable commonChildCheckParams = {};

    @observable gridlineVisible = true;
    @observable rowColHeaderVisible = true;
    @observable formatterSettingVisible = false;

    constructor() {
        this.addSelectOptionsStore = new AddSelectOptionsStore(this);
        this.addSelectTreeStore = new AddSelectTreeStore();
        this.addFixphareStore = new AddFixphareStore();
        this.templateBrowserStore.title = getLabel('503348', '选择Excel模板');
        each({ ...CommonAction }, (value, key) => {
            if (typeof value === 'function') {
                this[key] = action(value.bind(this));
            } else {
                this[key] = value;
            }
        });
        each({ ...TopActions }, (value, key) => {
            this[key] = action(value.bind(this));
        });
        each({ ...MenuAction }, (value, key) => {
            this[key] = action(value.bind(this));
        });

        this.aceEditorStore.parent = () => this;
        this.codeEditorStore.parent = () => this;
        //  this.fieldProps.parent = () => this;
        this.fieldAssignStore.parent = () => this;
    }

    @action
    loadWorkbook = (readonly) => {
        this.isInit = true;
        this.readonly = readonly;
        this.quickTableStore = new QuickTableStore(this);
    }
    @action loadDataSourceList = (id) => {
        if (id) {
            loadPageDs(id).then(list => {
                this.dataSourceList = list;
                if (this.workbook) {
                    this.reEnterCell();
                }
            });
        } else {
            this.dataSourceList = [];
        }
    }
    @action loadPageFieldAssignList = (id) => {
        if (id) {
            loadPageFieldAssign(id).then(list => {
                this.fieldAssignList = list;
                if (this.workbook) {
                    this.reEnterCell();
                }
            });
        } else {
            this.fieldAssignList = [];
        }
    }
    @action
    initWorkbook = (workbook) => {
        if (!workbook) {
            return;
        }
        this.workbook = workbook;
        window.workbookInstance = workbook;
        this.workbook.suspendPaint();
        this.workbook.sheets.forEach(sheet => {
            if (sheet.getColumnCount() < 50) {
                sheet.setColumnCount(50);
            }
            if (sheet.getRowCount() < 200) {
                sheet.setRowCount(200);
            }
        });
        this.workbook.resumePaint();
    }
    @action
    showPageById = (id) => {

        if (id) {
            this.loading = true;
            Promise.all(
                [API.pageInfo(id),
                FormulaAPI.loadFormula(id)]
            ).then(([page, list]) => {
                this.aceEditorStore.formulaList = list;
                this.showPage(page);
            })
        } else {
            this.showPage({ json: {} });
        }
    }

    @action
    newPage = () => {
        this.showPage({ json: {} });
        // 新建模板，将临时模板置空
        this.templateJSON = null;
    }

    reloadHeadTabs = (page) => {
        this.parent().getExcelPages(page, this.appid);
    }

    destoryWorkbook = () => {

        this.workbook = undefined;
    }
    @action
    showPage = (page) => {
        //console.log("page",page)
        this.fieldProps = new FieldPropsStore();
        this.fieldProps.parent = () => this;
        this.conditionDialogStore.parent = () => this;
        this.autoFitSheetMap = page.sheetSetting ? JSON.parse(page.sheetSetting) : {};
        if (typeof (page.rowControl) != 'undefined') {
            this.rowControl = JSON.parse(page.rowControl);
        }
        this.codeEditorStore.currentPageId = page.id;
        this.aceEditorStore.currentPageId = page.id;
        this.page = page;
        this.labels = page.labels || {};
        this.fieldName = page.fieldName || {};
        if (this.page && this.page.id) {
            this.disabledSignFields = true;
        } else {
            this.disabledSignFields = false;
        }

        if (!this.workbook) {
            setTimeout(() => {
                this.showPage(page);
            }, 50);
            return;
        }
        if (this.page && this.page.id) {
            this.dataSourceStore.reloadPageDsList = this.loadDataSourceList.bind(this, page.id);
            this.fieldAssignStore.reloadPageFieldAssignList = this.loadPageFieldAssignList.bind(this, page.id);
            this.loadDataSourceList(page.id);
            this.loadPageFieldAssignList(page.id);
        }
        const doAfters = this.loadFormula();
        const FieldCellType = CellType('FieldCellType');
        window.FieldCellType = FieldCellType;
        const NoFieldCellType = window.NoFieldCellType = CellType('NoFieldCellType');
        this.workbook.suspendPaint();
        page.json = (page.json && typeof page.json === 'string' && page.json.indexOf("{")<=-1 ) ? WeaTools.Base64.fromBase64(page.json) : page.json;
        const json = typeof page.json === 'string' ? JSON.parse(page.json) : page.json;
        this.workbook.fromJSON(json, false);
        const { sheets = {} } = json;
        each(sheets,(sheet,i)=>{
            const { index,name, __gridlineVisible=true, __rowColHeaderVisible=true } = sheet;
            const sheetObj = this.workbook.getSheet(index);
            sheetObj.options={...sheetObj.options,__gridlineVisible,__rowColHeaderVisible};
            const activeSheet = this.workbook.getActiveSheet();
            if(name === activeSheet.name()){
                this.gridlineVisible = __gridlineVisible;
                this.rowColHeaderVisible = __rowColHeaderVisible;
            }
        });
        this.workbook.sheets.forEach(sheet => {
            if (sheet.getColumnCount() < 50) {
                sheet.setColumnCount(50);
            }
            if (sheet.getRowCount() < 200) {
                sheet.setRowCount(200);
            }
            sheet.tables.all().forEach(table => {
                table.filterButtonVisible(false);
            });
        });
        const image = this.workbook.options.backgroundImage;
        this.workbook.options.backgroundImage = '';
        this.workbook.options.backgroundImage = image;
        this.workbook.bind(GC.Spread.Sheets.Events.EnterCell, this.enterCell);
        this.workbook.bind(GC.Spread.Sheets.Events.SheetNameChanged, this.sheetNameChanged);
        this.workbook.bind(GC.Spread.Sheets.Events.SheetNameChanging, this.SheetNameChanging);
        this.workbook.bind(GC.Spread.Sheets.Events.SelectionChanging, this.selectionChanging);
        this.workbook.bind(GC.Spread.Sheets.Events.SelectionChanged, this.selectionChanged);
        this.workbook.bind(GC.Spread.Sheets.Events.ActiveSheetChanged, this.activeSheetChange);
        register(this.workbook.commandManager());
        this.storeMenuData = [...this.workbook.contextMenu.menuData];
        this.reEnterCell();
        this.workbook.resumePaint();
        this.loading = false;
        doAfters.forEach(after => {
            after();
        })
        const activeSheet = this.workbook.getActiveSheet();
        const newSelections = activeSheet.getSelections();
        this.selectionChanging('', { newSelections });
        if (JSON.stringify(page.json) != "{}") {
            this.templateJSON = this.workbook.toJSON();
        }
        const sheetName = this.workbook.getActiveSheet().name();
        this.sheetAutoFit = this.autoFitSheetMap[sheetName];
        this.getSelectCelltypes();

        GC.Spread.Sheets.CellRange.prototype['fixed'] = function (fixed){
            const tag = this.tag() || {};
            if (fixed === void 0) {
                return !!(tag && tag.fixed);
            } else {
                this.tag({ ...tag, fixed });
                return this;
            }
        };

    }

    @action
    loadFormula = (list = this.aceEditorStore.formulaList) => {
        this.workbook.clearCustomFunctions();
        if (list) {
            return list.map(obj => {
                const TempFunction = CustomFunction(obj);
                return () => {
                    const func = new TempFunction(
                        obj.name, 0, 0, { name: obj.name, description: obj.describes }
                    );
                    this.workbook.addCustomFunction(func);
                };
            });
        }
        return [];
    }

    @action
    reEnterCell = () => {
        const sheet = this.workbook.getActiveSheet();
        const sheetName = sheet.name();
        const col = sheet.getActiveColumnIndex();
        const row = sheet.getActiveRowIndex();

        this.enterCell({}, {
            col,
            row,
            sheet,
            sheetName,
        });
    }

    @action
    getSelectCelltypes = () => {
        this.detailSelectCellTypeValueMap = {};
        this.detailSelectCellTypesMap = {};
        this.customdetailSelectCellTypeValueMap = {};
        this.customdetailSelectCellTypesMap = {};
        this.mainSelectCellTypeValueMap = {};
        this.mainSelectCellTypesMap = {};
        this.workbook.sheets.forEach(sheet => {
            // 明细表
            sheet.tables.all().forEach(table => {
                const bindingPath = table.bindingPath();
                if (bindingPath) {
                    const { col, colCount, row, rowCount } = table.dataRange();
                    for (let i = 0; i < colCount; i++) {
                        const cell = sheet.getCell(row, (col + i));
                        const cellType = cell.cellType();
                        if (cellType && cellType.getCellTypeName() == 'select' && cellType.fieldType && cellType.fieldType[2].datas) {
                            const fieldName = table.getColumnDataField(i);
                            if (!this.detailSelectCellTypeValueMap[bindingPath]) {
                                this.detailSelectCellTypeValueMap[bindingPath] = {};
                            }
                            this.detailSelectCellTypeValueMap[bindingPath][fieldName] = cellType.fieldType[2].datas.map(r => ({
                                key: r.selectName,
                                showname: r.selectName
                            }))

                            if (!this.detailSelectCellTypesMap[bindingPath]) {
                                this.detailSelectCellTypesMap[bindingPath] = [];

                            }
                            this.detailSelectCellTypesMap[bindingPath].push({
                                key: fieldName,
                                showname: cellType.label
                            })
                        }

                        if(cellType) {
                            // 明细表字段的多语言处理
                            const value = cellType.label;
                            const tag = cellType.multilang;
                            if(value && tag && tag.indexOf(value) > -1) {
                                //cucell.value(getCurrentLabel(tag))
                                let text = getCurrentLabel(tag);
                                if(!text) {
                                    text = getCurrentLabel(tag,"7")
                                }
                                cellType.label = text;
                                
                                table.setColumnName(i, text);
                            }
                        } 
                        
                    }
                } else if (table.name().startsWith("custom")) {
                    // 自定义明细表
                    const { col, colCount, row, rowCount } = table.dataRange();
                    const sheetName = sheet.name();
                    const tablename = table.name();
                    const mapName = sheetName + "." + tablename;
                    for (let j = 0; j < rowCount; j++) {
                        for (let i = 0; i < colCount; i++) {
                            const cell = sheet.getCell((row + j), (col + i));
                            const cellType = cell.cellType();
                            if (cellType && cellType.getCellTypeName() == 'select' && cellType.fieldType && cellType.fieldType[2].datas) {
                                const fieldName = this.getCustomFieldName(cell.bindingPath());
                                if (!this.customdetailSelectCellTypeValueMap[mapName]) {
                                    this.customdetailSelectCellTypeValueMap[mapName] = {};
                                }
                                this.customdetailSelectCellTypeValueMap[mapName][fieldName] = cellType.fieldType[2].datas.map(r => ({
                                    key: r.selectName,
                                    showname: r.selectName
                                }))

                                if (!this.customdetailSelectCellTypesMap[mapName]) {
                                    this.customdetailSelectCellTypesMap[mapName] = [];

                                }
                                this.customdetailSelectCellTypesMap[mapName].push({
                                    key: fieldName,
                                    showname: cellType.label
                                })
                            }

                            if(cellType) {
                                // 明细表字段的多语言处理
                                const value = cellType.label;
                                console.log(value)
                                const tag = cellType.multilang;
                                if(value && tag && tag.indexOf(value) > -1) {
                                    //cucell.value(getCurrentLabel(tag))
                                    let text = getCurrentLabel(tag);
                                    if(!text) {
                                        text = getCurrentLabel(tag,"7");
                                    }
                                    cellType.label = text;
                                }
                            } else {
                                //const cell = sheet.getCell(Number(rowIndex), Number(colIndex));
                                const value = cell.value();
                                const tag = cell.tag();
                                if(value && tag && tag.typeof==='string' &&tag.indexOf(value) > -1) {
                                    let text = getCurrentLabel(tag);
                                    if(!text) {
                                        text = getCurrentLabel(tag,"7")
                                    }
                                    cell.value(text);
                                }
                            }
                        }
                    }

                }

            });

            const { data } = sheet.toJSON();
            if (data) {
                const { dataTable } = data;
                if (dataTable) {
                    each(dataTable, (o, rowIndex) => {
                        each(o, (obj, colIndex) => {
                            const bindingPath = sheet.getBindingPath(rowIndex, colIndex);
                            if (bindingPath) {

                                const [sheetName, fieldName] = bindingPath.split('.');
                                const cell = sheet.getCell(rowIndex, colIndex);
                                const cellType = cell.cellType();
                                if (cellType && cellType.getCellTypeName() == 'select' && cellType.fieldType && cellType.fieldType[2].datas) {
                                    if (!this.mainSelectCellTypeValueMap[sheetName]) {
                                        this.mainSelectCellTypeValueMap[sheetName] = {};
                                    }
                                    this.mainSelectCellTypeValueMap[sheetName][fieldName] = cellType.fieldType[2].datas.map(r => ({
                                        key: r.selectName,
                                        showname: r.selectName
                                    }))

                                    if (!this.mainSelectCellTypesMap[sheetName]) {
                                        this.mainSelectCellTypesMap[sheetName] = [];

                                    }
                                    this.mainSelectCellTypesMap[sheetName].push({
                                        key: fieldName,
                                        showname: cellType.label
                                    })
                                }


                                if(cellType) {
                                    // 主表字段的多语言处理
                                    const cucell = sheet.getCell(Number(rowIndex), Number(colIndex));
                                    const cucellType = cucell.cellType();
                                    const value = cucellType.label;
                                    const tag = cucellType.multilang;
                                    if(value && tag && tag.indexOf(value) > -1) {
                                        //cucell.value(getCurrentLabel(tag))
                                        let text = getCurrentLabel(tag);
                                        if(!text) {
                                            text = getCurrentLabel(tag,"7")
                                        }
                                        cucellType.label = text;
                                    }
                                }
                                
                            } else {
                                // 常量字段
                                const cell = sheet.getCell(Number(rowIndex), Number(colIndex));
                                const value = cell.value();
                                const tag = cell.tag();
                                if(value && tag && tag.typeof==='string' && tag.indexOf(value) > -1) {
                                    let text = getCurrentLabel(tag);
                                    if(!text) {
                                        text = getCurrentLabel(tag,"7")
                                    }
                                    cell.value(text)
                                }
                            }

                        });
                    });

                }
            }
        });
    }


    getCustomFieldName = (bindingPath) => {
        let strs = bindingPath.split(".");
        return strs[strs.length - 1];

    }

    @action activeSheetChange = (e, info) => {
        const { newSheet, oldSheet } = info;
        this.sheetAutoFit = this.autoFitSheetMap[newSheet.name()];
        const {__gridlineVisible=true,__rowColHeaderVisible=true} = newSheet.options;
        this.gridlineVisible = __gridlineVisible;
        this.rowColHeaderVisible = __rowColHeaderVisible;
        this.reEnterCell();
    }

    @action SheetNameChanging = (e, info) => {
        const { sheet, newValue, oldValue, cancel } = info;
        if (newValue.indexOf('.') != -1 || newValue.startsWith(" ") || newValue.endsWith(" ")) {
            info.cancel = true;
        }
    }

    @action sheetNameChanged = (e, info) => {
        const { sheet, newValue, oldValue } = info;
        const { data } = sheet.toJSON();
        if (data) {
            const { dataTable } = data;
            if (dataTable) {
                each(dataTable, (o, rowIndex) => {
                    each(o, (obj, colIndex) => {
                        const bindingPath = sheet.getBindingPath(rowIndex, colIndex);
                        if (bindingPath) {
                            const [sheetName, fieldName] = bindingPath.split('.');
                            if (sheetName === oldValue) {
                                sheet.setBindingPath(rowIndex, colIndex, `${newValue}.${fieldName}`);
                            }
                        }

                    });
                });

            }
        }

        sheet.tables.all().forEach(table => {
            const bindingPath = table.bindingPath();
            if (bindingPath) {
                const paths = bindingPath.split('.');
                paths[0] = newValue;
                table.bindingPath(paths.join('.'));
            }
        });

        let tag = sheet.tag();
        if (tag) {
            if (this.sheetnameChangeRecord[tag]) {
                let oldSheetname = this.sheetnameChangeRecord[tag].oldSheetname;
                this.sheetnameChangeRecord[tag] = { oldSheetname: oldSheetname, newSheetname: newValue }
            } else {
                this.sheetnameChangeRecord[tag] = { oldSheetname: oldValue, newSheetname: newValue }
            }
        }

        // sheet自适应行高
        if(this.autoFitSheetMap) {
            const tmpMap = {}
            for(let key in this.autoFitSheetMap) {
                if(key == oldValue) {
                    tmpMap[newValue] = this.autoFitSheetMap[key];
                } else {
                    tmpMap[key] = this.autoFitSheetMap[key];
                }
            }
            this.autoFitSheetMap = tmpMap;
        }
        // 填报页面 sheet名不能修改
        // console.log(this.otherrightExpandMap);
        // if(this.otherrightExpandMap ) {
        //     for (let key in this.otherrightExpandMap) {
        //         const keys = key.split('.');
        //         if(keys[0] == oldValue) {
        //             const newKey = newValue + "." + keys[1]+"." + keys[2];
        //             this.otherrightExpandMap[newKey] = this.otherrightExpandMap[key];
        //             delete this.otherrightExpandMap[key];
        //         }
        //       }
        // }
        // console.log(this.otherrightExpandMap);
        // API.updateSheetName({
        //     pageid:this.page.id,
        //     oldSheetname:oldValue,
        //     newSheetname:newValue
        // })
        // const rowCount = sheet.getRowCount();
        // const colCount = sheet.getColumnCount();
        // for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) {
        //     for (let colIndex = 0; colIndex < colCount; colIndex++) {
        //         const bindingPath = sheet.getBindingPath(rowIndex, colIndex);
        //         if(bindingPath) {
        //             const [sheetName, fieldName] = bindingPath.split('.');
        //             if (sheetName === oldValue) {
        //                 sheet.setBindingPath(rowIndex, colIndex, `${newValue}.${fieldName}`);
        //             }
        //         }
        //     }
        // }
        // sheet名变化，下拉款关系数据也需要变化
        this.getSelectCelltypes();
    }
    @action selectionChanging = (e, info) => {
        const { newSelections } = info;
        const selection = newSelections[0];
        this.selection = `${selection.rowCount}*${selection.colCount}`
    }

    @action
    selectionChanged = (e, info) => {

        if (this.isformatpainter) {
            const sheet = this.workbook.getActiveSheet();
            sheet.isPaintSuspended(true);
            let toRange = sheet.getSelections()[0];


            //toRange biger than fromRange
            if (this.fromRange.rowCount > toRange.rowCount) {
                toRange.rowCount = this.fromRange.rowCount;
            }
            if (this.fromRange.colCount > toRange.colCount) {
                toRange.colCount = this.fromRange.colCount;
            }
            //toRange must in Sheet
            if (toRange.row + toRange.rowCount > sheet.getRowCount()) {
                toRange.rowCount = sheet.getRowCount() - toRange.row;
            }
            if (toRange.col + toRange.colCount > sheet.getColumnCount()) {
                toRange.colCount = sheet.getColumnCount() - toRange.col;
            }


            this.workbook.commandManager().execute({
                cmd: "formatpainter",
                sheetName: sheet.name(),
                sheet: sheet,
                fromSheet: this.fromSheet,
                fromRanges: this.fromRange,
                toRange: toRange,
                isCutting: false,
                clipboardText: "",
            });

            // let rowStep = this.fromRange.rowCount, colStep = this.fromRange.colCount;
            // let endRow = toRange.row + toRange.rowCount - 1, endCol = toRange.col + toRange.colCount - 1;

            // // if toRange bigger than fromRange, repeat paint
            // for(let startRow = toRange.row; startRow <= endRow; startRow = startRow + rowStep){
            //     for(let startCol = toRange.col; startCol <= endCol; startCol = startCol + colStep){

            //         let rowCount = startRow + rowStep > endRow + 1 ? endRow - startRow + 1 : rowStep;
            //         let colCount = startCol + colStep > endCol + 1 ? endCol - startCol + 1 : colStep;
            //         // sheet.copyTo(fromRange.row,fromRange.col, startRow, startCol, rowCount, colCount,GC.Spread.Sheets.CopyToOptions.style | GC.Spread.Sheets.CopyToOptions.span);
            //         let fromRanges = new GC.Spread.Sheets.Range(this.fromRange.row, this.fromRange.col, rowCount, colCount);
            //         let pastedRange = new GC.Spread.Sheets.Range(startRow, startCol, rowCount, colCount);
            //         this.workbook.commandManager().execute({
            //             cmd: "formatpainter",
            //             sheetName: sheet.name(),
            //             sheet:sheet,
            //             fromSheet: this.fromSheet,
            //             fromRanges: fromRanges,
            //             pastedRanges: pastedRange,
            //             isCutting: false,
            //             clipboardText: "",
            //         });
            //     }
            // }

            sheet.isPaintSuspended(false);
        }

        this.isformatpainter = false;
    }

    @action
    enterCell = (e, info) => {
        const { row, col, sheet } = info;
        const range = sheet.getCell(row, col);
        const cellType = range.cellType();
        // const rowControl =this.rowControl;
        let cellTypeName = undefined;
        const FieldCellType = CellType('FieldCellType');
        const isField = cellType instanceof FieldCellType;
        let showname = '';
        let fieldtype = "";
        let field = "";
        if (isField) {
            cellTypeName = cellType.getCellTypeName();
        }
        const undoManager = this.workbook.undoManager();
        this.undoDisabled = !undoManager.canUndo();
        this.redoDisabled = !undoManager.canRedo();
        const font = range.font();
        const vAlign = range.vAlign();
        const hAlign = range.hAlign();
        const underline = range.textDecoration();
        const fontObj = getFont(font);
        const table = sheet.tables.find(row, col);
        const { fixed,formatter,formatterType } = range.tag()||{};
        this.activeCellStyle = {
            bold: fontObj.fontWeight === 'bold',
            fontFamily: fontObj.fontFamily,
            fontSize: fontObj.fontSize,
            hAlign,
            italic: fontObj.fontStyle === 'italic',
            spanCell: !!info.sheet.getSpan(range.row, range.col),
            underline: underline === GC.Spread.Sheets.TextDecorationType.underline,
            vAlign,
            wordwrap: range.wordWrap(),
            cellTypeName,
            combineSameCell: !!(isField && table && cellType.combineSameCell),
            combineSameCellDisabled: !(isField && table && cellTypeName!='image'),
            fixedCell: fixed,
            formatter: formatter,
            formatterType: formatterType
        };
        this.isAutoFillinDisabled = true;
        if (isField && cellTypeName && (cellTypeName === 'select' || (cellTypeName.indexOf('browser') == 0 && cellTypeName != 'browser290'))) {
            this.isAutoFillinDisabled = false;
            this.isAutoFillin = !!cellType.autoFillin;
        }
        this.setFieldTypeDisabled = false;
        let currentSingleCell;
        if (table) {
            if (table.bindingPath()) {

                setRightMenu(this, "1", row <= table.dataRange().row);
            } else if (table.name().startsWith("custom")) {
                setRightMenu(this, "2", row <= table.dataRange().row);
            }
            this.activeCellName = `${getCellName(range.row, range.col)}(${table.name()})`;
            if (table.bindingPath()) {
                this.clearFieldDisabled = true;
            } else {
                this.clearFieldDisabled = false;
            }
            this.deleteTableDisabled = false;
            currentSingleCell = sheet.getCell(table.dataRange().row, col);
        } else {
            setRightMenu(this, "0");
            this.activeCellName = getCellName(range.row, range.col);
            this.clearFieldDisabled = false;
            this.deleteTableDisabled = true;
            currentSingleCell = range;
        }
        const fillinArea = false;
        if (this.fieldProps) {
            const fieldPropsType = table ? FieldPropsType.Detail : fillinArea ? FieldPropsType.FillinArea : FieldPropsType.Main;
            this.fieldProps.initProps(this.dataSourceList, range, table, this.rowControl);
        }

        if (this.fieldAssignStore) {
            const sheetName = sheet.name();
            const currentCellType = currentSingleCell.cellType();
            const isCurrentField = currentCellType instanceof FieldCellType;
            if (isCurrentField) {
                //点击字段，保存字段属性，fieldtype：mainfield/detailfield/cellfield,showname,field
                const { detailIndex, detailName, fieldName, label } = currentCellType;
                // showname = sheetName+'.'+cellType.detailName();
                showname = `${sheetName}.${detailName}.${fieldName}(${label})`;

                if (detailIndex) {
                    fieldtype = 'detailfield';
                    field = `${sheetName}.detail_${detailIndex}.${fieldName}`;
                } else {
                    fieldtype = 'mainfield';
                    field = `${sheetName}.${fieldName}`;
                }
            } else {
                fieldtype = 'cellfield';
                showname = `${sheetName}.${getCellName(range.row, range.col)}`;
                field = `${sheetName}.${getCellName(range.row, range.col)}`;
            }
            const { visible } = this.fieldAssignStore;
            if (visible) {
                const { props, state, onChangeState } = this.excelCellSelect;
                const { tableCellProps } = props;
                const { text, record, index, onEdit } = tableCellProps;
                onEdit({
                    type: "CUSTOM",
                    record: {
                        ...record,
                        showname: showname,
                        fieldtype: fieldtype,
                        field: field
                    },
                    index,
                    key: "customrender",
                    value: 1
                });
                onChangeState();
                const { scrollTop } = record;
                setTimeout(() => {
                    $('.ant-table-body').scrollTop(scrollTop);
                }, 50);
                if (props.onChangeSize) {
                    props.onChangeSize('normal');
                }
            }
        }

        this.commonChildCheckParams = {//处理commonChildCheckParams
            detailtable: cellType&&cellType.tableName?cellType.tableName:`edc_uf_table${sheet.tag()<0?sheet.tag()*(-1):sheet.tag()}`,
            fieldhtmltype: 5,
            billid: sheet.tag()||'',
            isdetail: cellType&&cellType.detailIndex? 1 : 0,
            isbill: 1,
            fieldid: cellType&&cellType.id?cellType.id:'',
        }
        if (table) {
            const { name } = table.toJSON();
            const index = name.charAt(name.length - 1);
            this.commonChildCheckParams.detailtable = `edc_uf_table${sheet.tag()<0?sheet.tag()*(-1):sheet.tag()}_dt${index}`;
            this.commonChildCheckParams.isdetail = 1;
        }

    }
    undo = () => {
        this.workbook.undoManager().undo();
        this.reEnterCell();
    }
    redo = () => {
        this.workbook.undoManager().redo();
        this.reEnterCell();
    }

    setGridline = (visible) => {
        const sheet = this.workbook.getActiveSheet();
        sheet.options={...sheet.options,__gridlineVisible:visible};
    }
    setRowColHeaderVisible = (visible) => {
        const sheet = this.workbook.getActiveSheet();
        sheet.options={...sheet.options,__rowColHeaderVisible:visible};
    }
    setBackGroundImage = (img) => {
        const sheet = this.workbook.getActiveSheet();
        const [selection] = sheet.getSelections();
        if (selection) {
            const { row, col, rowCount, colCount } = selection;
            this.workbook.suspendPaint();
            if (row === -1 && col === -1) {
                this.workbook.options.backgroundImage = '';
                this.workbook.options.backgroundImage = img;
            } else {
                sheet.getRange(row, col, rowCount, colCount).backgroundImage(img);
            }
            this.workbook.resumePaint();
        }
    }
    setBackGroundImageLayout = (layout) => {
        const sheet = this.workbook.getActiveSheet();
        const [selection] = sheet.getSelections();
        if (selection) {
            const { row, col, rowCount, colCount } = selection;
            this.workbook.suspendPaint();
            if (row === -1 && col === -1) {
                this.workbook.options.backgroundImageLayout = layout;
            } else {
                sheet.getRange(row, col, rowCount, colCount).backgroundImageLayout(layout);
            }
            this.workbook.resumePaint();
        }
    }
    getActiveSheet = () => {
        return this.workbook && this.workbook.getActiveSheet();
    }
    @action toggleFormatterSettingDialog = (visible) => {
        if (visible === void 0) {
            this.formatterSettingVisible = !this.formatterSettingVisible;
        } else {
            this.formatterSettingVisible = visible;
        }
    }
    setFormatter= (formatter, formatterType) => {
        this.changeCellStyle({ formatter:{formatter,formatterType} });
    }
}